package com.yootk;
import java.util.concurrent.*;

public class YootkDemo16 {
    public static void main(String[] args) throws Exception {
        int repeat = 2;
        Exchanger<String> exc = new Exchanger<>();

        // 信息生产者线程
        new Thread(() -> {
            for (int y = 0; y < repeat; y++) {
                String info = null;
                if (y % 2 == 0) {
                    info = "李兴华高薪就业编程训练营：edu.yootk.com";
                } else {
                    info = "沐言科技：www.yootk.com";
                }
                try {
                    System.out.println("【" + Thread.currentThread().getName() + "】准备发送：" + info);
                    // 交换信息
                    exc.exchange(info);
                    System.out.println("【" + Thread.currentThread().getName() + "】发送完成：" + info);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "信息生产者").start();

        // 信息消费者线程
        new Thread(() -> {
            for (int y = 0; y < repeat; y++) {
                try {
                    System.out.println("【" + Thread.currentThread().getName() + "】等待接收数据...");
                    // 交换信息（null表示只接收不发送）
                    String info = exc.exchange(null);
                    System.out.println("【" + Thread.currentThread().getName() + "】接收到：" + info);
                    TimeUnit.SECONDS.sleep(1); // 模拟处理时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "信息消费者").start();
    }
}